import pygame
from pygame.locals import *
from sys import exit
from mastergoal.gui.grid import Grid
from mastergoal.gui.entities import *
from mastergoal.gui.events import *
from mastergoal.common.piece import *
from mastergoal.common.square import Square
from mastergoal.common.board import Board
from mastergoal.common.team import Team
from mastergoal.common.state import State
import os

pygame.init()
SCREEN_SIZE = (1024,620)
BOARD_INIT_POS = (120,10)
BOARD_DELTA = (10, 10)

class Game:
    def __init__(self):
        
        """ Initialize game objects. Create instances of pieces and 
        associate them to entities, which contains information about 
        surface and position """
        
        self.piece_clicked = None
        self.running = True
        self.pieces_gui = []
        
        # Grid initialization
        grid_position = (BOARD_INIT_POS[0]+BOARD_DELTA[0], BOARD_INIT_POS[1]+BOARD_DELTA[1])
        grid_size = (15,11)
        sqr_size = (39,39)
        
        self.grid = Grid(grid_position, grid_size, sqr_size)
        self.grid.load()
        
        # Start screen
        self.screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
        pygame.display.set_caption("Mastergoal")
        
        # Create pieces and entities
        self.init_game_properties()
        
        self.clock = pygame.time.Clock()
        self.speed = 90.
        self.ui_events = UIEvent(self)
        
    def init_game_properties(self):
        
        ball = BallPiece(Square(7,5))
        self.pieces_gui.append(BallEntity(ball, 'ball2.png'))
        
        board = Board(ball)
        self.board_obj = BoardEntity(board, 'board.jpg', BOARD_INIT_POS)
        
        team_1 = Team(Team.DOWN, "red")
        team_2 = Team(Team.UP, "white")
       
        # Player creation
        player = PlayerPiece(PlayerPiece.G, Square(3,5))
        team_1.add_player(player)
        self.pieces_gui.append(PieceEntity(player, 'r1.gif') )
        
        player = PlayerPiece(PlayerPiece.R, Square(4,3))
        team_1.add_player(player)
        self.pieces_gui.append(PieceEntity(player, 'r2.gif'))
        
        player = PlayerPiece(PlayerPiece.L, Square(6,2))
        team_1.add_player(player)
        self.pieces_gui.append(PieceEntity(player, 'r3.gif'))
        
        player = PlayerPiece(PlayerPiece.P, Square(4,7))
        team_1.add_player(player)
        self.pieces_gui.append(PieceEntity(player, 'r4.gif'))
        
        player = PlayerPiece(PlayerPiece.N, Square(6,8))
        team_1.add_player(player)
        self.pieces_gui.append(PieceEntity(player, 'r5.gif'))

        board.add_team(team_1)
        
        player = PlayerPiece(PlayerPiece.G, Square(11,5))
        team_2.add_player(player)
        self.pieces_gui.append(PieceEntity(player, 'w1.gif') )
        
        player = PlayerPiece(PlayerPiece.R, Square(10,3))
        team_2.add_player(player)
        self.pieces_gui.append(PieceEntity(player, 'w1.gif'))
        
        player = PlayerPiece(PlayerPiece.L, Square(8,2))
        team_2.add_player(player)
        self.pieces_gui.append(PieceEntity(player, 'w1.gif'))
        
        player = PlayerPiece(PlayerPiece.P, Square(10,7))
        team_2.add_player(player)
        self.pieces_gui.append(PieceEntity(player, 'w1.gif'))
        
        player = PlayerPiece(PlayerPiece.N, Square(8,8))
        team_2.add_player(player)
        self.pieces_gui.append(PieceEntity(player, 'w1.gif'))
        
        board.add_team(team_2)
        
        # Create game state
        self.state = State(board, level=2)
        
        self.set_pieces_position()

        
    def set_pieces_position(self):
        """ Loop GUI pieces and sets their position in terms of coordinates """
        for piec_obj in self.pieces_gui:
            key = str(piec_obj.piece.square.row) + '_' + str(piec_obj.piece.square.col)
            piec_obj.position = Rect(self.grid[key])
            
    def show_objects(self):
        """ Display objects on screen """
        # Show board
        self.screen.blit(self.board_obj.image, self.board_obj.position)

        # Show piece objects
        for obj in self.pieces_gui:
            
            time_passed_sec = self.clock.tick(100) / 1000.0
            distance_moved = time_passed_sec * self.speed
            
            if obj.moving:
#                print "time passed %s " % time_passed_sec
#                print "distance moved %s " % distance_moved
#                print "obj_heading[0] %s" % obj.heading[0] 
                x_step, y_step = obj.heading[0] * distance_moved, obj.heading[1] * distance_moved
#                print "x_step %s - y_step " % x_step, y_step
                if obj.move_current[0] + x_step <= obj.move_delta[0] and \
                    obj.move_current[1] + y_step <= obj.move_delta[1]:
#                        print "obj.position %s" % obj.position
                        obj.position.left += x_step
                        obj.position.top += y_step
                        #obj.move_current = [ obj.move_current[i] + obj.heading[i]*distance_moved for i in range(len(obj.move_current)) ]
                        obj.move_current[0] += abs(x_step)
                        obj.move_current[1] += abs(y_step)
                else:
                    obj.moving = False
                    obj.position.left = obj.destination[0]
                    obj.position.top = obj.destination[1]
            self.screen.blit(obj.image, obj.position)
                    
            
          
    def run(self):
        """ Main loop inside pygame """
        while self.running:
            
            for event in pygame.event.get():
                
                if event.type == QUIT:
                    exit()
                  
                if event.type == MOUSEBUTTONDOWN:  
                    self.ui_events.handle(event)
                    
            self.screen.fill((0,0,0))
            self.show_objects()
            #self.grid.show(self.screen)
            pygame.display.update()  
                    
        
def main():
    """ Activity wrapper """
    game = Game()
    game.run()

if __name__ == "__main__":
    main()
    

       
            
        
    
    